package com.liaogui.consumer;

import com.google.gson.Gson;
import com.liaogui.api.UserService;
import com.liaogui.framework.Invocation;
import com.liaogui.framework.protocol.AbstractLoadBalance;
import com.liaogui.framework.protocol.HttpClient;
import com.liaogui.framework.protocol.RandomLoadBalance;
import com.liaogui.framework.register.RedisClient;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 * @author liaogui
 * @date 2025/4/17 16:09
 */
public class ProxyFactory<T> {
    public static <T> T getProxy(final Class interfaceClass) {
        return (T) Proxy.newProxyInstance(ProxyFactory.class.getClassLoader(),
                new Class[]{interfaceClass},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Invocation sayHello = new Invocation(interfaceClass.getName(),
                                method.getName(),
                                method.getParameterTypes(),
                                args,
                                "");
                        RedisClient redisClient = new RedisClient("127.0.0.1", 6379, "umbs123", 2);
                        String service = redisClient.discoverService(interfaceClass.getName());
                        List<String> list = new Gson().fromJson(service, List.class);
                        // TODO 负载均衡算法
                        RandomLoadBalance loadBalance = new RandomLoadBalance();
                        URL url = loadBalance.doSelect(list);
                        HttpClient httpClient = new HttpClient();
                        return httpClient.send(url, sayHello);
                    }
                });

    }

    public static void main(String[] args) throws MalformedURLException {
        String url = "http://127.0.0.1:8085";
        java.net.URL url1 = new java.net.URL(url);
        System.out.println(url1);
    }
}
